package controllers

import (
	"os"
	"path"
	"time"

	"github.com/astaxie/beego"
)

type UploadController struct {
	beego.Controller
}

/**
 *	注释：图片上传页面
 *	时间：2018-04-06
 *	作者：Haojie Li
 */
func (c *UploadController) UploadImgPage() {
	c.TplName = "uploadImg.tpl"
}

/**
 *	注释：图片上传 （有待改善）
 *	时间：2018-04-06
 *	作者：Haojie Li
 */
func (this *UploadController) ImgUpload() {

	f, h, err := this.GetFile("imgFile")

	out := make(map[string]interface{})
	if err != nil {
		out["msg"] = "文件读取错误"
	}
	var fileSuffix, newFile string
	fileSuffix = path.Ext(h.Filename) //获取文件后缀

	newFile = time.Now().Format("yyyyMMddHHmmss") + fileSuffix
	//创建上传目录
	os.Mkdir("/upload", os.ModePerm)

	err = this.SaveToFile("imgFile", "/upload/"+newFile)
	out["msg"] = "ok"
	if err != nil {
		out["msg"] = "文件保存错误"
	}
	defer f.Close()
	out["state"] = "SUCCESS"
	out["url"] = "/upload/" + newFile
	out["title"] = newFile
	out["original"] = h.Filename
	out["size"] = h.Size

	this.Data["json"] = out
	this.ServeJSON()
	this.StopRun()

}
